import { login, logout, getInfo } from '@/api/acl/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter,constantRoutes,allAsyncRoutes,anyRoute} from '@/router'
import router from '@/router'
import cloneDeep from 'lodash/cloneDeep'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    roles:[],
    buttons:[],
    routes:[],  //最终放的是路由器里面配置的所有路由  不是字符串
    asyncRoutes:[], //它里面放的是用户最终匹配好的异步路由  不是字符串
  }
}

function filterAsyncRoutes(allAsyncRoutes,routeNames){
  //专门根据用户的路由权限信息（字符串），过滤出用户真正的自己的异步路由
  let asyncRoutes = allAsyncRoutes.filter(item => {
    if(routeNames.indexOf(item.name) !== -1){
      if(item.children && item.children.length){
        // 过滤出子路由把原来所有的子路由覆盖掉
        item.children = filterAsyncRoutes(item.children,routeNames) 
      }
      return true
    }
  })
  return asyncRoutes
}


const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    // assign 功能：合并对象
    // 参数：两个  第一个是目标对象  第二个是源对象
    // 返回值： 返回目标对象
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  // SET_NAME: (state, name) => {
  //   state.name = name
  // },
  // SET_AVATAR: (state, avatar) => {
  //   state.avatar = avatar
  // }

  SET_USERINFO(state,userInfo){
    state.name = userInfo.name
    state.avatar = userInfo.avatar
    state.roles = userInfo.roles
    state.buttons = userInfo.buttons
  },


  SET_ROUTES(state,asyncRoutes){
    state.asyncRoutes = asyncRoutes //所有匹配成功的路由对象组成的数组
    state.routes = constantRoutes.concat(asyncRoutes,anyRoute) //所有的路由对象，生成菜单使用的
    //动态添加路由到路由器里面（动态注册路由），因为我们现在注册的只有常量路由
    router.addRoutes([...asyncRoutes,anyRoute]) //动态的添加路由
  }


}

const actions = {
  async login({commit},userInfo){
    const { username, password } = userInfo
    const result = await login({ username: username.trim(), password: password })
    console.log(result);
    if(result.code === 20000 || result.code === 200){
      const { data } = result
      commit('SET_TOKEN', data.token)
      setToken(data.token)
      return 'ok'
    }else{
      return Promise.reject(new Error('failed'))
    }
  },



  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response
        if (!data) {
          return reject('Verification failed, please Login again.')
        }
        commit('SET_USERINFO',data)
        commit('SET_ROUTES',filterAsyncRoutes(cloneDeep(allAsyncRoutes),data.routes))

        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

